package com.tyanxie.asd.activity

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.room.Room
import com.tyanxie.asd.adapter.HistoryAdapter
import com.tyanxie.asd.config.IDataBase
import com.tyanxie.asd.databinding.ActivityHistoryBinding

class HistoryActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityHistoryBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 获取数据库控制器
        val database = Room.databaseBuilder(this, IDataBase::class.java, "sugar")
            .allowMainThreadQueries()
            .build()
        val sugarNumberDao = database.sugarNumberDao()
        val sugarEntityDao = database.sugarEntityDao()

        // 清空按钮
        binding.ahDeleteIv.setOnClickListener {
            sugarEntityDao.truncate()
            sugarNumberDao.truncate()
            (binding.ahRv.adapter as HistoryAdapter).clear()
        }

        // 获取数据
        val sugarNumbers = sugarNumberDao.all()
        sugarNumbers.forEach {
            if (it.id != null) {
                it.sugarEntities = sugarEntityDao.listBySugarNumberId(it.id)
            }

        }

        // 配置recyclerView
        binding.ahRv.adapter = HistoryAdapter(this, sugarNumbers)
        binding.ahRv.layoutManager = LinearLayoutManager(this)
    }
}